//
//  ContactsTableViewController.m
//  Only Love
//
//  Created by 郭健 on 16/5/11.
//  Copyright © 2016年 海城. All rights reserved.
//

#import "ContactsTableViewController.h"
#import "AddContactsViewController.h"
#import "ContactModel.h"

#import "EaseMessageViewController.h"
#import "ChatViewController.h"
@interface ContactsTableViewController ()

@property (nonatomic,retain)NSMutableArray *allContactsArray;       //存储所有联系人的数组
@property (nonatomic,strong)NSMutableArray *allDBContactsArray;     //从服务器获取联系人信息的数组

@end

@implementation ContactsTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor grayColor];
    self.navigationItem.title = @"私聊";

    /** 在视图右上角增加添加按钮*/
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addContactsAction:)];
    
    //监听登录成功的消息
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(successLogin) name:@"successLogin" object:nil];
    
    /**  监听通知中心的断开连接的消息 */
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(disConn:) name:@"disConnection" object:nil];
    
    /** 监听刷新好友列表的通知*/
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshList) name:@"refreshContactsList" object:nil];
    
    //注册单元格
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"CELL"];
    [self.tableView reloadData];
    [self successLogin];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self refreshList];
}
 
-(void)successLogin{

    /** 获取联系人列表*/
    EMError *error = nil;
    NSArray *buddyList = [[EaseMob sharedInstance].chatManager fetchBuddyListWithError:&error];
    if (!error) {
         [self.allContactsArray removeAllObjects];
        NSLog(@"获取成功 -- %@",buddyList);
        for (EMBuddy *userName in self.allContactsArray) {
            ContactModel *model = [[ContactModel alloc]init];
            model.contactName = userName.username;
            
            [self.allContactsArray addObject:model];
            [self.tableView reloadData];
        }
        NSLog(@"获取联系人成功");
    }else{
         NSLog(@"获取联系人失败");
    }
    [self.tableView reloadData];
}

-(void)refreshList{

    //重新从服务器获得联系人列表
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        EMError *error;
        NSArray *tempArray = [[EaseMob sharedInstance].chatManager fetchBuddyListWithError:&error];
        
        NSLog(@"获取成功 --  %@",tempArray);
        if (error) {
//            NSLog(@"刷新用户列表出错 -- %d",error.code);
        }else{
            
            NSLog(@"刷新获取用户成功");
            //本地的可变数组中原有的联系人删除干净
            //要添加新用户了，将旧的删除掉
            [self.allContactsArray removeAllObjects];
//            NSLog(@"%@",[EaseMob sharedInstance].currentUsername);
            for (EMBuddy *contactName in tempArray) {
                ContactModel *model = [[ContactModel alloc]init];
                model.contactName = contactName.username;
                [self.allContactsArray addObject:model];
                NSLog(@"name %@",model.contactName);
            }
        }
        [self.tableView reloadData];


    });

}








#pragma mark -- 懒加载
-(NSMutableArray *)allContactsArray{
    
    if (!_allContactsArray) {
        _allContactsArray = [[NSMutableArray alloc]init];
    }
    return _allContactsArray;
}
-(NSMutableArray *)allDBContactsArray{
    
    if (!_allDBContactsArray) {
        _allDBContactsArray = [[NSMutableArray alloc]init];
    }
    return _allDBContactsArray;
}


#pragma mark -- 添加按钮的回调方法
-(void)addContactsAction:(UIBarButtonItem *)sender{
    
    AddContactsViewController *addContactsVC =[[AddContactsViewController alloc]init];
    UINavigationController *navC = [[UINavigationController alloc]initWithRootViewController:addContactsVC];
    [self presentViewController:navC animated:YES completion:nil];
}

#pragma mark -- 通知中心的回调方法
-(void)disConn:(NSNotification *)notification{
    //    self.navigationItem.title = @"正在连接网络......";
    NSDictionary *dic = notification.userInfo;
    int connState = [dic[@"conn"] intValue];
    if (connState == 0) {   //已连接
        self.navigationItem.title = @"通讯录";
    }else{
        self.navigationItem.title =@"正在连接网络 ......";
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
   return self.allContactsArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL" forIndexPath:indexPath];
    
    //从数组中取出model
    ContactModel *model = [self.allContactsArray objectAtIndex:indexPath.row];
    cell.textLabel.text = model.contactName;
    return cell;
}



/** 点击单元格的代理方法*/
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ContactModel *model = [self.allContactsArray objectAtIndex:indexPath.row];
   
//    ChatViewController *chatVC = [[ChatViewController alloc]initWithConversationChatter:model.contactName conversationType:eConversationTypeChat];
//    chatVC.title = model.contactName;
////    [self.navigationController  pushViewController:chatVC animated:YES];
//    [self presentViewController:chatVC animated:YES completion:nil];
    ChatViewController *chatVC = [[ChatViewController alloc]initWithConversationChatter:model.contactName conversationType:eConversationTypeChat];
    
    chatVC.title = model.contactName;
//    chatVC.tabBarController.tabBar.hidden = YES;
//    [self.navigationController  pushViewController:chatVC animated:YES];
    UINavigationController *navC = [[UINavigationController alloc]initWithRootViewController:chatVC];
    [self presentViewController:navC animated:YES completion:nil];

}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
